package org.lcc.Controller;

import org.lcc.Service.ExaminationmanagementService;
import org.lcc.model.VO.*;
import org.lcc.model.dto.*;
import org.lcc.model.entity.Class;
import org.lcc.model.entity.Exam;
import org.lcc.model.entity.Question;
import org.lcc.model.request.AddExamQuestionRequest;
import org.lcc.util.ApiResponseMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

import java.util.List;

@RestController
@RequestMapping()
@Tag(name = "考试管理", description = "考试相关的接口")
public class ExaminationmanagementController {
    @Autowired
    private ExaminationmanagementService examinationmanagementService;

    @Operation(summary = "创建考试", description = "创建一个新的考试")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/createExam")
    public ApiResponseMe createExam(@RequestBody ExamDto examDto) {
        if (examDto == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        Integer ExamId = examinationmanagementService.createExam(examDto);
        if (ExamId != null) {
            return ApiResponseMe.success(ExamId);
        }
        return ApiResponseMe.shape(false, "创建失败");
    }

    @Operation(summary = "获取题库列表", description = "根据教师ID获取其创建的题库列表")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "题库创建者信息缺失")
    })
    @GetMapping("/showExam")
    public ApiResponseMe showExam(
        @Parameter(description = "教师ID", required = true)
        @RequestParam("schoolNumber") String schoolNumber) {
        if (schoolNumber == null) {
            return ApiResponseMe.error(400, "题库创建者信息缺失,请检查该用户是否已经创建了题库");
        }
        List<QuestionVO> questionVOList = examinationmanagementService.showExam(schoolNumber);
        return ApiResponseMe.success(questionVOList);
    }

    @Operation(summary = "获取题型统计", description = "获取指定题库中各题型的数量统计")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "题库不存在")
    })
    @GetMapping("/getNumberOfDifferentTypes")
    public ApiResponseMe getNumberOfDifferentTypes(
        @Parameter(description = "题库名称", required = true)
        @RequestParam("question_name") String question_name) {
        List<QuestionDataVo> questionDataVoList = examinationmanagementService.getNumberOfDifferentTypes(question_name);
        if (questionDataVoList == null || questionDataVoList.isEmpty()) {
            return ApiResponseMe.error(400, "题库不存在");
        }
        return ApiResponseMe.success(questionDataVoList);
    }

    @Operation(summary = "随机组题", description = "根据指定的题量信息随机生成试题")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "组题成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/randomQuestion")
    public ApiResponseMe randomQuestion(
        @Parameter(description = "题量信息", required = true)
        @RequestBody QuestionBankDto questionBankDto,
        @Parameter(description = "考试ID", required = true)
        @RequestParam("ExamId") Integer ExamId) {
        if (questionBankDto == null || ExamId == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        try {
            Boolean randomQuestion = examinationmanagementService.randomQuestion(questionBankDto, ExamId);
            if (!randomQuestion) {
                return ApiResponseMe.shape(randomQuestion, "试题设置失败,请检查相关信息");
            }
            return ApiResponseMe.shape(randomQuestion, "考试设置成功,可发布考试");
        } catch (RuntimeException e) {
            return ApiResponseMe.error(400, e.getMessage());
        }
    }

    @Operation(summary = "获取手动选题列表", description = "获取指定题库中可供手动选择的题目列表")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @GetMapping("/getManualQuestion")
    public ApiResponseMe getManualQuestion(
        @Parameter(description = "题库名称", required = true)
        @RequestParam("question_name") String question_name) {
        if (question_name == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        List<QuestionTypemanualVo> questionTyp = examinationmanagementService.getManualQuestion(question_name);
        if (questionTyp != null) {
            return ApiResponseMe.success(questionTyp);
        }
        return ApiResponseMe.success("当前题库无试题");
    }

    @Operation(summary = "手动选题", description = "手动选择试题添加到考试中")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "选题成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/manualQuestion")
    public ApiResponseMe manualQuestion(
        @Parameter(description = "考试ID", required = true)
        @RequestParam("ExamId") Integer ExamId,
        @Parameter(description = "题目ID列表", required = true)
        @RequestBody QuestionIdDto question_id) {
        if (ExamId == null || question_id == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        System.out.println(question_id);
        try {
            Boolean b = examinationmanagementService.manualQuestion(ExamId, question_id);
            return ApiResponseMe.shape(b, "考试设置成功,可发布考试");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ApiResponseMe.error(400, e.getMessage());
        }
    }

    @Operation(summary = "获取考试预览", description = "获取指定考试的试题预览")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "未获取到考试ID")
    })
    @GetMapping("/getExamPreview")
    public ApiResponseMe getExamPreview(
        @Parameter(description = "考试ID", required = true)
        @RequestParam("examId") Integer examId) {
        if (examId == null) {
            return ApiResponseMe.error(400, "未获取到考试ID");
        }
        List<QuestionPreviewVo> previewData = examinationmanagementService.getExamPreview(examId);
        if (previewData == null || previewData.isEmpty()) {
            return ApiResponseMe.shape(true, "该考试暂未添加试题");
        }
        System.out.println(previewData);
        return ApiResponseMe.success(previewData);
    }

    @Operation(summary = "发布考试", description = "发布指定考试")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "发布成功"),
        @ApiResponse(responseCode = "400", description = "发布失败")
    })
    @PostMapping("/publish")//
    public ApiResponseMe publishExam(
        @Parameter(description = "发布信息", required = true)
        @RequestBody PubishExamDto pub) {
        try {
            PublishExamResultDto result = examinationmanagementService.publishExam(pub);
            if (result.getSuccess()) {
                return ApiResponseMe.success(result);
            } else {
                return ApiResponseMe.error(400,result.getMessage());
            }
        } catch (Exception e) {
            return ApiResponseMe.error(400,"发布考试失败：" + e.getMessage());
        }
    }
    // 获取当前老师创建的考试列表
    @Operation(summary = "获取老师创建的考试列表", description = "获取考试列表")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "获取失败")
    })
    @GetMapping("/getExamList")
    public ApiResponseMe getExamList(@Parameter (description = "教师ID", required = true)
                                     @RequestParam("schoolNumber") String teacherId,
                                     @Parameter (description = "考试状态", required = false)
                                     @RequestParam(value = "status", required = false) String status,
                                     @Parameter (description = "页码", required = false)
                                     @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @Parameter (description = "每页条数", required = false)
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     @Parameter (description = "搜索文本", required = false)
                                     @RequestParam (value = "searchText", required = false) String searchText) {
        if (teacherId == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        List<ExamVO> examvo = examinationmanagementService.getteacherIdExam(teacherId, status, pageNum, pageSize,searchText);
        if (examvo == null) {
            return ApiResponseMe.shape(true, "该老师暂未创建的考试");
        }
        return ApiResponseMe.success(examvo);
    }
    @Operation(summary = "获取学生考试列表", description = "获取学生需要进行的考试列表")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @GetMapping("/getExamstudent")
    public ApiResponseMe getExam(
        @Parameter(description = "学生学号", required = true)
        @RequestParam("schoolNumber") String schoolNumber) {
        if (schoolNumber == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        List<ExamListVo> examvo = examinationmanagementService.getExam(schoolNumber);
        if (examvo == null) {
            return ApiResponseMe.shape(true, "该考生暂未需要进行的考试");
        }
        return ApiResponseMe.success(examvo);
    }
    @Operation(summary = "获取考试试题", description = "获取指定考试的试题内容")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @GetMapping("/getExamQuestion")
    public ApiResponseMe getExamQuestion(
        @Parameter(description = "考试ID", required = true)
        @RequestParam("examId") Integer examId) {
        if (examId == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        ExamQuestionVO examQuestionVO = examinationmanagementService.getExamQuestion(examId);
        if (examQuestionVO == null) {
            return ApiResponseMe.shape(true, "试题内容有误,请联系相关试题创建老师.");
        }
        return ApiResponseMe.success(examQuestionVO);
    }

    @Operation(summary = "提交答案", description = "提交考试答案")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "提交成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/submitAnswer")
    public ApiResponseMe submitAnswer(
        @Parameter(description = "答案信息", required = true)
        @RequestBody AnswerDto answerDto) {
        if (answerDto == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        System.out.println(answerDto);
        String scoreInquiryID = examinationmanagementService.submitAnswer(answerDto);
        if (scoreInquiryID == null) {
            return ApiResponseMe.shape(false, "试题提交失败,请检查相关信息");
        }
        return ApiResponseMe.success(scoreInquiryID);
    }
    //获取考生已经作答的考试
    @Operation(summary = "获取考生已经作答的考试", description = "获取考生已经作答的考试")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @GetMapping("/getExamstudentAnswer")
    public ApiResponseMe getExamstudentAnswer(
        @Parameter(description = "学生学号", required = true)
        @RequestParam("schoolNumber") String schoolNumber) {
        if (schoolNumber == null) {
            return ApiResponseMe.error(400, "数据无效");
        }
        List<ExamRecordoneVO> examvo = examinationmanagementService.getExamstudentAnswer(schoolNumber);
        if (examvo == null) {
            return ApiResponseMe.shape(true, "暂未查询到数据");
        }
        return ApiResponseMe.success(examvo);
    }
    @Operation(summary = "获取主观题", description = "获取考试中的主观题")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @GetMapping("/getSubjectiveQuestion")
    public ApiResponseMe getSubjectiveQuestion(
        @Parameter(description = "考试ID", required = true)
        @RequestParam("examId") Integer examID,@RequestParam("studentId") String studentID) {
        if (examID == null) {
            return ApiResponseMe.error(400, "数据无效");
        }

        List<Subjective_questionVo> subjectiveQuestion = examinationmanagementService.seletQuery_subjective(examID, studentID);
        if (subjectiveQuestion == null) {
            return ApiResponseMe.shape(true, "该老师暂未创建过考试");
        }
        return ApiResponseMe.success(subjectiveQuestion);
    }
    @Operation(summary = "更新考试状态(人工评卷)", description = "更新考试状态和分数")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "数据无效")
    })
    @PostMapping("/updateExamStatus")
    public ApiResponseMe updateExamStatus(
        @Parameter(description = "主观题答案列表", required = true)
        @RequestBody List<SubjectiveAnswerDto> subjectiveAnswerDto) {
        if (subjectiveAnswerDto == null){
            return ApiResponseMe.error(400,"数据无效");
        }
        Boolean b = examinationmanagementService.updateExamStatus(subjectiveAnswerDto);
        if (b){
            return ApiResponseMe.success("评卷成功");
        }
        return ApiResponseMe.error(400,"评卷失败");
    }
    //处理主观题为空的情况
    @PostMapping("/updateExamStatusNUll")
    public ApiResponseMe updateExamStatusNUll(@RequestParam("examId") String examId,@RequestParam("schoolNumber") String schoolNumber) {
        if (examId == null || schoolNumber == null){
            return ApiResponseMe.error(400,"数据无效");
        }
        Boolean b = examinationmanagementService.updateExamStatusNull(examId,schoolNumber);
        if (b){
            return ApiResponseMe.success("评卷成功");
        }
        return ApiResponseMe.error(400,"评卷失败");
    }

    @Operation(summary = "获取教师班级", description = "获取教师创建的所有班级")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "500", description = "获取失败")
    })
    @GetMapping("/getTeacherClasses")
    public ApiResponseMe getTeacherClasses(
        @Parameter(description = "教师ID", required = true)
        @RequestParam("teacherId") String teacherId) {
        try {
            List<Class> classes = examinationmanagementService.getTeacherClasses(teacherId);
            return ApiResponseMe.success(classes);
        } catch (Exception e) {
            return ApiResponseMe.error(500, "获取班级列表失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取教师学生", description = "获取教师所有班级中的学生")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "500", description = "获取失败")
    })
    @GetMapping("/getTeacherStudents")//202309031477
    public ApiResponseMe getTeacherStudents(
        @Parameter(description = "教师ID", required = true)
        @RequestParam("teacherId") String teacherId) {
        try {
            List<StudentVO> students = examinationmanagementService.getTeacherStudents(teacherId);
            return ApiResponseMe.success(students);
        } catch (Exception e) {
            return ApiResponseMe.error(500, "获取学生列表失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取考试详情", description = "根据考试ID获取考试详情")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "获取失败")
    })
    @GetMapping("/getExamDetail")
    public ApiResponseMe getExamDetail(@Parameter(description = "考试ID", required = true)
                                     @RequestParam("examId") Integer examId) {
        if (examId == null) {
            return ApiResponseMe.error(400, "考试ID不能为空");
        }
        ExamVO examVO = examinationmanagementService.getExamDetail(examId);
        if (examVO == null) {
            return ApiResponseMe.error(400, "考试不存在");
        }
        return ApiResponseMe.success(examVO);
    }

    @Operation(summary = "更新考试信息", description = "更新考试基本信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "400", description = "更新失败")
    })
    @PutMapping("/updateExam")
    public ApiResponseMe updateExam(@RequestBody Exam exam) {
        if (exam == null || exam.getExamId() == null) {
            return ApiResponseMe.error(400, "考试信息不完整");
        }
        boolean success = examinationmanagementService.updateExamInfo(exam);
        if (!success) {
            return ApiResponseMe.error(400, "更新失败");
        }
        return ApiResponseMe.success("更新成功");
    }

    /**
     * 获取老师创建的所有题库
     */
    @Operation(summary = "获取老师创建的所有题库", description = "根据老师工号获取创建的所有题库")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "获取失败")
    })
    @GetMapping("/questionBanks")
    public ApiResponseMe getQuestionBanks(@Parameter(description = "老师工号", required = true)
            @RequestParam String teacherId) {
        try {
            List<QuestionVO> questionBanks = examinationmanagementService.getQuestionBanks(teacherId);
            return ApiResponseMe.success(questionBanks);
        } catch (Exception e) {
            return ApiResponseMe.error(400,"获取题库列表失败");
        }
    }

    /**
     * 获取指定题库中的所有试题
     */
    @Operation(summary = "获取指定题库中的所有试题", description = "根据题库名获取指定题库中的所有试题")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "获取失败")
    })
    @GetMapping("/questionsByBank")
    public ApiResponseMe getQuestionsByBank(@Parameter(description = "老师工号", required = true)
            @RequestParam String questionBankName) {
        try {
            List<Question> questions = examinationmanagementService.getQuestionsByBank(questionBankName);
            return ApiResponseMe.success(questions);
        } catch (Exception e) {
            return ApiResponseMe.error(400,"获取试题列表失败");
        }
    }
    /**
     * 添加考试试题
     */
    @PostMapping("/examquestionadd")
    public ApiResponseMe addExamQuestions(@RequestBody AddExamQuestionRequest request) {
        try {
            boolean success = examinationmanagementService.addExamQuestions(request);
            if (success) {
                return ApiResponseMe.success("添加试题成功");
            } else {
                return ApiResponseMe.error(400,"添加试题失败");
            }
        } catch (Exception e) {
            return ApiResponseMe.error(400,"添加试题失败：" + e.getMessage());
        }

    }
    //删除试题

    @DeleteMapping("/exam/question/delete")
    public ApiResponseMe deleteQuestion(@RequestBody ExamQuestionDeleteDTO request) {
        try {
            examinationmanagementService.deleteQuestion(request.getExamId(), request.getQuestionId());
            return ApiResponseMe.success("删除试题成功");
        } catch (Exception e) {
            return ApiResponseMe.error(400,e.getMessage());
        }
    }
    //删除考试
    @DeleteMapping("/exam/delete")
    public ApiResponseMe deleteExams(@RequestBody ExamDeleteDTO request) {
        try {
            examinationmanagementService.deleteExams(request.getExamIds());
            return ApiResponseMe.success("删除考试成功");
        } catch (Exception e) {
            return ApiResponseMe.error(400,"删除考试失败: " + e.getMessage());
        }
    }
    //最近考试获取
    @GetMapping("/recent-exams")
    public ApiResponseMe getRecentExams(@RequestParam(required = false) String schoolNumber) {
        try {
            List<Exam> recentExams = examinationmanagementService.getRecentExams(schoolNumber);
            return ApiResponseMe.success(recentExams);
        } catch (Exception e) {
            return ApiResponseMe.error(400,"获取最近考试失败");
        }
    }
}
